package com.codeoss.framework.controller;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.codeoss.framework.response.FileResponse;
import com.codeoss.framework.service.IFileService;
import com.codeoss.framework.util.IOUtil;
import com.codeoss.framework.util.StringUtils;

@Controller
@RequestMapping("file")
public class FileController {
	@Autowired
	private IFileService fileService;
	@RequestMapping(value = "download", method = RequestMethod.GET)
	@ResponseBody
	public void download(@RequestParam("filename") String filename,@RequestParam(required=false) String displayName,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)throws Exception {
		FileResponse fileResponse=fileService.download(filename);
		httpServletResponse.reset();
		try {
			if(StringUtils.isEmpty(displayName)) {
				httpServletResponse.addHeader("Content-Disposition","attachment;filename="+new String(filename.getBytes(),"ISO-8859-1"));
			}else {
				httpServletResponse.addHeader("Content-Disposition","attachment;filename="+new String(displayName.getBytes(),"ISO-8859-1"));
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		OutputStream out=httpServletResponse.getOutputStream();
		InputStream is=null;
		try {
			is=fileResponse.getInputStream();
			byte[] b=new byte[1024];
			int len;
			while((len=is.read(b))!=-1) {
				out.write(b, 0, len);
			}
		}catch(Exception e) {
			throw e;
		}finally {
			IOUtil.closeInputStream(is);
		}
	}
}
